package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.domain.Setmeal;
import com.itheima.domain.SetmealDish;
import com.itheima.dto.SetmealDto;
import com.itheima.mapper.SetmealMapper;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SetmealServiceimpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    public void updateWithSetmeal(SetmealDto setmealDto) {
        updateById(setmealDto);
        System.out.println(111111);
        LambdaQueryWrapper<SetmealDish> setmealDishlqw = new LambdaQueryWrapper<>();
        setmealDishlqw.eq(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(setmealDishlqw);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
//        setmealDishes.forEach(item -> item.setSetmealId(setmealDto.getId());
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    public SetmealDto getByIdWithSetmeal(Long id) {
        Setmeal setmeal = getById(id);

        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);

        LambdaQueryWrapper<SetmealDish> setmealDishLqw = new LambdaQueryWrapper<>();
        setmealDishLqw.eq(SetmealDish::getSetmealId, setmeal.getId());
        List<SetmealDish> list = setmealDishService.list(setmealDishLqw);
        setmealDto.setSetmealDishes(list);
        return setmealDto;
    }

}
